<template>
    <el-container>
        <el-main>
            <el-row style="margin-bottom: 20px;">
                <div style="font-weight: bold;margin-top: 4px;">数据库名称</div>
                <el-select v-model="databaseModel.name" placeholder="请先选择数据库" @change="changeDatabase"
                    style="width: 240px;float:left;margin-left:20px;">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-icon @click="init" size="20" 
                    style="margin-top: 5px;margin-left: 8px; cursor: pointer">
                    <Refresh></Refresh>
                </el-icon>
            </el-row>
            <el-row justify="space-between"
                style="border-bottom: 1px solid #e0e0e0;padding-bottom: 10px;margin-bottom: 10px;">
                <el-col :span="8">
                    <span style="font-weight: bold;">建库和建表</span>
                </el-col>
                <el-col :span="16">
                    <div style="display:flex;justify-content: flex-end;">
                        <el-button type="primary" @click="dialogVisible = true">初始化库</el-button>
                        <el-button type="warning" plain @click="createTables">执行建表</el-button>
                    </div>
                </el-col>
            </el-row>
            <!--建表配置-->
            <el-form :inline="true" :model="tableModel" label-width="auto">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="表前缀">
                            <el-input v-model="tableModel.prefix" placeholder="表前缀" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="建表数量">
                            <el-input v-model="tableModel.count" placeholder="建表数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="建表起始索引">
                            <el-input v-model="tableModel.index" placeholder="建表数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="分配比例：（f,d,i,b）">
                            <el-input v-model="tableModel.ratio" placeholder="分配比例" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>

            <el-row style="border-bottom: 1px solid #e0e0e0;margin-bottom: 10px;">
                <el-col :span="16">
                    <span style="font-weight: bold;">实时写入测试</span>
                    <el-button type="primary" plain style="margin-left:20px;"
                        @click="addTaskDialogOpen">新增任务</el-button>

                    <el-button type="danger" plain style="margin-left:20px;" @click="flushTask">刷新</el-button>

                    <el-button type="info" plain style="margin-left:20px;" @click="selectRealData">实时数据性能查询</el-button>
                </el-col>
                <el-col :span="8" style="margin-bottom: 5px;">
                    <div style="display:flex;justify-content: flex-end;">
                        <el-button type="primary" @click="btn_startAllTask()">全部开始</el-button>
                        <el-button type="warning" plain @click="btn_stopAllTask()">全部停止</el-button>
                    </div>
                </el-col>
            </el-row>
            <!--实时写入测试-->
            <el-table :data="tableData" :width="dialogWidth" height="400" border>
                <template #empty>
                    <el-empty />
                </template>
                <el-table-column prop="name" label="任务" width="150" align="center">
                </el-table-column>
                <el-table-column prop="startIndex" label="起始表索引" width="100" align="center">
                </el-table-column>
                <el-table-column prop="taskCount" label="数量" width="100" align="center">
                </el-table-column>
                <el-table-column prop="taskThread" label="线程数量" width="100" align="center">
                </el-table-column>
                <el-table-column prop="taskPeriod" label="写入周期(秒)" width="150" align="center">
                </el-table-column>
                <el-table-column prop="taskMocktype" label="数据模拟" width="100" align="center">
                    <template v-slot="scope">
                        <!-- {{ getStatusText(scope.row.status) }} 写方法进行显示值替换 -->
                        {{ scope.row.taskMocktype === '0' ? '随机数' : scope.row.taskMocktype === '1' ? '固定值0' : scope.row.taskMocktype === '2' ? '固定值1' : scope.row.taskMocktype === '3' ? '布尔随机数' : scope.row.taskMocktype    }}
                    </template>
                </el-table-column>
                <el-table-column prop="taskStatue" label="状态" width="100" align="center"
                    :filters="[{ text: '启动', value: '启动' }, { text: '停止', value: '停止' }]" filter-placement="bottom-end">
                    <template v-slot="scope">
                        <el-tag :type="scope.row.taskStatue === '启动' ? 'primary' : 'info'"
                            disable-transitions>{{ scope.row.taskStatue }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="taskLastwritetime" label="最后写入时间" width="300" align="center"
                    :formatter="formatDate">
                </el-table-column>
                <el-table-column fixed="right" label="操作" minWidth="300" align="center">
                    <template v-slot="scope">
                        <!-- <el-button type="primary" plain @click="btn_showTables(scope.row)">查看子表</el-button> -->
                        <el-button type="primary" plain @click="btn_startTask(scope.row)">启动</el-button>
                        <el-button type="danger" plain @click="btn_stopTask(scope.row)">停止</el-button>
                        <el-button type="primary" @click="btn_editTask(scope.row)">编辑</el-button>
                        <el-button type="danger" plain @click="btn_deleteTask(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>


            <!-- 写入规则 -->
            <el-row justify="space-between" style="border-bottom: 1px solid #e0e0e0;margin: 14px 0;">
                <el-col :span="8">
                    <span style="font-weight: bold;">历史写入测试</span>
                </el-col>
                <el-col :span="8" :offset="8" style="margin-bottom: 5px;">
                    <div style="display: flex;justify-content: flex-end;align-items: center;">
                        <!-- v-if="!taskIsDoing" -->
                        <el-tag style="margin-right: 8px;">批量插入耗时:{{batchInsertTime}}ms</el-tag>
                        <el-button type="primary" @click="batchInsert">批量插入</el-button>
                        <el-button type="primary" @click="beginWrite">执行写入</el-button>
                        <el-button type="primary" @click="stopWrite"
                            :style="{ backgroundColor: 'red', color: 'white' }">取消执行</el-button>
                    </div>
                </el-col>
            </el-row>
            <!--历史数据写入配置-->
            <el-form :inline="true" :model="writeRules" label-width="auto">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="写入表的数量">
                            <el-input v-model="writeRules.tableCount" placeholder="写入表的数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="起始表索引">
                            <el-input v-model="writeRules.index" placeholder="起始表索引" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="分线程数量">
                            <el-input v-model="writeRules.threadCount" placeholder="分线程数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="数据模拟">
                            <el-select v-model="writeRules.mockType" placeholder="数据模拟" class="formItem">
                                <el-option label="随机数" value="0"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="写入周期">
                            <el-input v-model="writeRules.period" placeholder="写入周期" class="formItem">
                                <template v-slot:append>秒</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="开始时间">
                            <el-date-picker v-model="writeRules.startDatetime" type="datetime" placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="结束时间">
                            <el-date-picker v-model="writeRules.endDatetime" type="datetime" placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-main>
        <el-dialog v-model="dialogVisible" title="数据库配置信息" width="80%" draggable>
            <el-form :inline="true" :model="databaseModel" label-width="150px">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="数据库名称">
                            <el-input v-model="databaseModel.name" placeholder="数据库名称"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库ip">
                            <el-input disabled v-model="databaseModel.host" placeholder="数据库ip"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库端口号">
                            <el-input disabled v-model="databaseModel.port" placeholder="数据库端口号"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="先执行删除库操作">
                            <el-switch v-model="databaseModel.isDelete"></el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="数据库用户名">
                            <el-input disabled v-model="databaseModel.username" placeholder="数据库用户名"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数据库密码">
                            <el-input disabled v-model="databaseModel.password" placeholder="数据库密码"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="VGROUPS">
                            <el-input v-model="databaseModel.vgroups" class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="BUFFER">
                            <el-input v-model="databaseModel.buffer" class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="CACHEMODEL">
                            <!-- <el-input v-model="databaseModel.cachemodel" class="formItemDialog"></el-input> -->
                            <el-select v-model="databaseModel.cachemodel" placeholder="缓存模式" class="formItemDialog">
                                <el-option label="不缓存" value="none"></el-option>
                                <el-option label="last_row" value="last_row"></el-option>
                                <el-option label="last_value" value="last_value"></el-option>
                                <el-option label="both" value="both"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="CACHESIZE">
                            <el-input v-model="databaseModel.cachesize" class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">

                    </el-col>
                    <el-col :span="spanLength">

                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                    </el-col>
                    <el-col :span="12">
                        <el-button style="float: right;margin-left: 10px;" @click="dialogVisible = false">关闭</el-button>
                        <el-button style="float: right;" type="primary" @click="initDatbase">确定</el-button>
                    </el-col>

                </el-row>
            </el-form>
        </el-dialog>

        <el-dialog v-model="taskDialogVisible" title="实时写入配置信息" width="80%" draggable>
            <el-form :inline="true" :model="taskModel" label-width="150px">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="任务名称">
                            <el-input v-model="taskModel.name" placeholder="任务名称" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="起始表索引">
                            <el-input v-model="taskModel.startIndex" placeholder="起始表索引" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数量">
                            <el-input v-model="taskModel.taskCount" placeholder="数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="表前缀">
                            <el-input v-model="taskModel.taskPrefix" placeholder="表前缀"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="线程">
                            <el-input v-model="taskModel.taskThread" placeholder="线程" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="写入周期(秒)">
                            <el-input v-model="taskModel.taskPeriod" placeholder="写入周期(秒)" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="数据模拟">
                            <el-select v-model="taskModel.taskMocktype" placeholder="数据模拟" class="formItem">
                                <el-option label="随机数" value="0"></el-option>
                                <el-option label="固定值0" value="1"></el-option>
                                <el-option label="固定值1" value="2"></el-option>
                                <el-option label="布尔随机值" value="3"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="状态">
                            <el-input disabled v-model="taskModel.taskStatue" placeholder="状态"
                                class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="模拟周期(秒)">
                            <el-input v-model="taskModel.mnPeriod" placeholder="模拟周期" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                    </el-col>
                    <el-col :span="12">
                        <el-button style="float: right;margin-left: 10px;"
                            @click="taskDialogVisible = false">关闭</el-button>
                        <el-button style="float: right;" type="primary" @click="addTask">确定</el-button>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>

        <el-dialog v-model="realDataVisible" title="实时数据查询配置" width="80%" draggable>
            <el-form :inline="true" :model="realDataModel" label-width="150px">
                <el-row>
                    <el-col :span="spanLength">
                        <el-form-item label="起始表索引">
                            <el-input v-model="realDataModel.startIndex" placeholder="起始表索引" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="spanLength">
                        <el-form-item label="数量">
                            <el-input v-model="realDataModel.taskCount" placeholder="数量" class="formItem"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="spanLength">
                        <el-form-item label="线程">
                            <el-input v-model="realDataModel.taskThread" placeholder="线程" class="formItemDialog"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                    </el-col>
                    <el-col :span="12">
                        <el-button style="float: right;margin-left: 10px;"
                            @click="realDataVisible = false">关闭</el-button>
                        <el-button style="float: right;" type="primary" @click="getRealData">确定</el-button>

                        <el-tag style="margin-right: 8px;">实时查询耗时:{{batchSelectTime}}ms</el-tag>
                    </el-col>
                </el-row>
            </el-form>
        </el-dialog>
    </el-container>
</template>

<script lang="ts" setup>
import { initTdengineDatbase, createTdengineTables, beginTDengineWrite, stopTDengineWrite, getTDengineWriteStatus } from '@/api/mock'
import { addTaskInfo, readRealData, searchTaskInfo, deleteTask, startTask, stopTask, startAllTask, stopAllTask, batchInsertInfoWrite, getDoingCount } from '@/api/task'
import { ref, watch, onMounted, defineProps } from 'vue';
import { showDatabases } from '@/api/index'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'

//属性值
const props = defineProps({
	dbInfo:{
		type:Object,
		default:{},
	},
	databaseInfo:{
		type:Array,
		default:[]
	}
})
const store = {
	info:props.dbInfo,
	databaseInfo: props.databaseInfo
}
const dialogVisible = ref(false)
const dialogWidth = ref(0);
const tableData = ref([]);

const taskDialogVisible = ref(false)


/**
 * 连接数据库信息
 */
const connInfo = ref(store.info.value);
const databaseModel = ref({ name: "", isDelete: false, host: "", port: "", username: "", password: "", vgroups: 4, buffer: 256,cachesize:1,cachemodel:"last_row" });
const tableModel = ref({ prefix: "TAG_", count: "100000", ratio: "10:0:0:0", index: 0 });
const writeRules = ref({ tableCount: "10000", index: "0", threadCount: "3", mockType: "0", period: "1", startDatetime: null, endDatetime: null });
const spanLength = ref(6);
const batchInsertTime = ref(0);
const batchSelectTime = ref(0);
const initDatbaseLoading = ref(false);
const createTablesLoading = ref(false);
const beginWriteLoading = ref(false);
const realDataVisible = ref(false);
const taskIsDoing = ref(false);
const options = ref([]);

const taskModel = ref({
    name: "",
    startIndex: 0,
    taskCount: 30000,
    taskPeriod: 1,
    taskMocktype: "0",
    taskThread: 3,
    taskStatue: "停止",
    taskPrefix: tableModel.value.prefix,
    mnPeriod: 1
})
const realDataModel = ref({
        startIndex: 0,
        taskCount: 100000,
        taskThread: 1,
        taskPrefix: tableModel.value.prefix,
    })

onMounted(() => {
    if (!store.connected || !store.info) {
        connInfo.value = {
            host: '',
            port: '',
            username: '',
            password: ''
        }
    } else {
        connInfo.value = store.info;
    }
    // 布局宽度
    dialogWidth.value = document.documentElement.clientWidth * 0.8 - 10;
    setTimeout(() => {
        init()
    }, 100);

    getWriteStatus()
    //   setInterval(() => {
    //     getWriteStatus()
    //   }, 5000);

})

watch((deep) => store.info, val => {
    // 改变数据库连接信息，监听联动
    if (val && store.connected) {
        init();
    }
})

const init = () => {
    console.log('init')
    connInfo.value = store.info;
    initDatabaseModel();
    /**
   * 连接数据库
   */
    let payload = store.info;
    if (payload.host != null && payload.host != "" && payload.host != "''") {
        showDatabases(payload).then(r => {
            if (r.code == 200) {
                options.value = r.data.map((item: any, index: number) => {
                    return {
                        value: item,
                        label: item,
                    };
                });
            }
        });
    }
}

const initDatabaseModel = () => {
    databaseModel.value.host = connInfo.value.host;
    databaseModel.value.port = connInfo.value.port;
    databaseModel.value.username = connInfo.value.username;
    databaseModel.value.password = connInfo.value.password;
}

//根据数据库名称和表前缀来唯一定位任务 
const getWriteStatus = () => {
    searchAllTask();
}
/**
 * 任务刷新
 */
const flushTask = () => {
    searchAllTask();
    ElMessage({
        message: '刷新任务成功',
        type: 'success',
    });
}

const selectRealData= () => {
    realDataModel.value = {
        startIndex: 0,
        taskCount: 100000,
        taskThread: 1,
        taskPrefix: tableModel.value.prefix,
    };
    realDataVisible.value = true;
}
const getRealData = () =>{
    batchSelectTime.value = 0;
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    var params = realDataModel.value;
    params['tDengineConfigDto'] = databaseModel.value;
    readRealData(params).then(res => {
        if (res.code == '200') {
            ElMessage({
                message: res.data,
                type: 'success',
            });
            
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
        loading.close();
        batchSelectTime.value = res.data;
    }).catch(res => {
        loading.close()
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}
/**
 * 数据库切换
 * @param val 
 */
const changeDatabase = (val) => {
    databaseModel.value.name = val;
    searchAllTask();
}
/**
 * 初始化库
 */
const initDatbase = () => {
    ElMessageBox.confirm('请确认是否初始化当前数据库?')
        .then(() => {
            initDBInfo();
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })

}
const initDBInfo = () => {
    if (initDatbaseLoading.value) {
        return
    }
    if (!justifyInitDatabaseParamsValid()) {
        return
    }

    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    initDatbaseLoading.value = true;
    initTdengineDatbase(databaseModel.value).then(res => {
        if (res.code == '200') {
            ElMessage({
                message: res.data,
                type: 'success',
            });
            init();
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
        initDatbaseLoading.value = false;
        dialogVisible.value = false;
        loading.close();
    }).catch(res => {
        initDatbaseLoading.value = false;
        dialogVisible.value = false;
        loading.close()
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}
//初始化表
const createTables = () => {
    ElMessageBox.confirm('请确认建表规则,执行建表！')
        .then(() => {
            createTablesInfo();
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })

}
const createTablesInfo = () => {
    if (createTablesLoading.value)
        return
    if (!justifyCreateTablesParamsValid() || !justifyInitDatabaseParamsValid())
        return
    createTablesLoading.value = true;
    var params = tableModel.value;
    params['tDengineConfigDto'] = databaseModel.value;
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    createTdengineTables(params).then(res => {
        if (res.code == '200') {
            ElMessage({
                message: res.data,
                type: 'success',
            });
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
        createTablesLoading.value = false;
        loading.close();
    }).catch(res => {
        createTablesLoading.value = false;
        loading.close();
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}
//执行写入操作
const beginWrite = () => {
    ElMessageBox.confirm('请确认写入规则,执行实时值的写入！')
        .then(() => {
            beginWriteInfo();
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })
}
const beginWriteInfo = () => {
    if (beginWriteLoading.value)
        return
    if (!justifyCreateTablesParamsValid() || !justifyInitDatabaseParamsValid() || !justifyWriteRulesParamsValid())
        return
    beginWriteLoading.value = true
    var params = tableModel.value
    params['tDengineConfigDto'] = databaseModel.value
    var params2 = writeRules.value
    params2['createTableDto'] = params
    beginTDengineWrite(params2).then(res => {
        if (res.code == '200') {
            ElMessage({
                message: res.data,
                type: 'success',
            });
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
        beginWriteLoading.value = false;
    }).catch(res => {
        beginWriteLoading.value = false;
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}

//取消写入
const stopWrite = () => {
    if (databaseModel.value.name == undefined || databaseModel.value.name == "" || tableModel.value.prefix == undefined || tableModel.value.prefix == "") {
        ElMessage({
            message: "数据库名称和表前缀不能为空",
            type: 'warning',
        });
        return
    }
    var params = tableModel.value;
    params['tDengineConfigDto'] = databaseModel.value
    stopTDengineWrite(params).then(res => {
        if (res.code == '200') {
            taskIsDoing.value = false
            ElMessage({
                message: res.data,
                type: 'success',
            });
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
    }).catch(res => {
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}


//校验必填字段信息
const justifyInitDatabaseParamsValid = () => {
    if (databaseModel.value.name == undefined || databaseModel.value.name == "") {
        ElMessage({
            message: "数据库名称不能为空",
            type: 'warning',
        });
        return false
    }
    if (databaseModel.value.host == undefined || databaseModel.value.host == "") {
        ElMessage({
            message: "数据库ip不能为空",
            type: 'warning',
        });
        return false
    }
    if (databaseModel.value.port == undefined || databaseModel.value.port == "") {
        ElMessage({
            message: "数据库端口不能为空",
            type: 'warning',
        });
        return false
    }
    if (databaseModel.value.username == undefined || databaseModel.value.username == "") {
        ElMessage({
            message: "数据库用户名不能为空",
            type: 'warning',
        });
        return false
    }
    if (databaseModel.value.password == undefined || databaseModel.value.password == "") {
        ElMessage({
            message: "数据库密码不能为空",
            type: 'warning',
        });
        return false
    }

    return true
}
//建表字段信息的校验
const justifyCreateTablesParamsValid = () => {
    if (tableModel.value.prefix == undefined || tableModel.value.prefix == "") {
        ElMessage({
            message: "表前缀不能为空",
            type: 'warning',
        });
        return false
    }
    if (tableModel.value.count == undefined || tableModel.value.count == "") {
        ElMessage({
            message: "表数量不能为空",
            type: 'warning',
        });
        return false
    }
    if (tableModel.value.ratio == undefined || tableModel.value.ratio == "") {
        ElMessage({
            message: "表比例不能为空",
            type: 'warning',
        });
        return false
    }

    const regex = /^\d+:\d+:\d+:\d+$/;
    if (!regex.test(tableModel.value.ratio)) {
        ElMessage({
            message: "比例格式不对，必须是类似格式 6:2:1:1",
            type: 'warning',
        });
        return false
    }

    return true
}

//写入规则的校验
const justifyWriteRulesParamsValid = () => {
    if (writeRules.value.tableCount == undefined || writeRules.value.tableCount == "") {
        ElMessage({
            message: "写入表数量不能为空",
            type: 'warning',
        });
        return false
    }
    if (writeRules.value.index == undefined || writeRules.value.index == "") {
        ElMessage({
            message: "起始索引不能为空",
            type: 'warning',
        });
        return false
    }
    if (writeRules.value.threadCount == undefined || writeRules.value.threadCount == "") {
        ElMessage({
            message: "线程数不能为空",
            type: 'warning',
        });
        return false
    }
    if (writeRules.value.mockType == undefined || writeRules.value.mockType == "") {
        ElMessage({
            message: "模拟方式不能为空",
            type: 'warning',
        });
        return false
    }
    if (writeRules.value.period == undefined || writeRules.value.period == "") {
        ElMessage({
            message: "周期不能为空",
            type: 'warning',
        });
        return false
    }
    if (writeRules.value.startDatetime == undefined || writeRules.value.startDatetime == null) {
        ElMessage({
            message: "开始时间不能为空",
            type: 'warning',
        });
        return false
    }

    if (writeRules.value.endDatetime == undefined || writeRules.value.endDatetime == null) {
        ElMessage({
            message: "结束时间不能为空",
            type: 'warning',
        });
        return false
    }
    return true
}

/**
 * 查询当前的所有任务
 */
const searchAllTask = () => {
    if (databaseModel.value.name != null && databaseModel.value.name != "" && databaseModel.value.host != null && databaseModel.value.host != "") {
        var params = tableModel.value
        params['tDengineConfigDto'] = databaseModel.value
        searchTaskInfo(params).then(r => {
            tableData.value = r.data.map((item: any, index: number) => {
                return item;
            });
        }).catch(err => {
            ElMessage({
                message: '查询任务失败',
                type: 'error',
            });
        });
    }
}
/**
 * 开启新增任务弹窗
 */
const addTaskDialogOpen = () => {
    taskModel.value = {
        name: "",
        startIndex: 0,
        taskCount: 30000,
        taskPeriod: 1,
        taskMocktype: "0",
        taskThread: 3,
        taskStatue: "停止",
        taskPrefix: tableModel.value.prefix,
        mnPeriod: 1
    };
    taskDialogVisible.value = true;
}
const addTask = () => {
    if (!ParamsValid()) {
        return
    }
    ElMessageBox.confirm('确认是否提交任务记录?')
        .then(() => {
            addTaskRecord();
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })
}
const addTaskRecord = () => {


    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    var params = taskModel.value;
    params['tDengineConfigDto'] = databaseModel.value;
    addTaskInfo(params).then(res => {
        if (res.code == '200') {
            ElMessage({
                message: res.data,
                type: 'success',
            });
            taskDialogVisible.value = false;
            searchAllTask();
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
            taskDialogVisible.value = false;
        }
        loading.close();
    }).catch(res => {
        taskDialogVisible.value = false;
        loading.close()
        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}
//校验必填字段信息
const ParamsValid = () => {
    if (taskModel.value.name == undefined || taskModel.value.name == "") {
        ElMessage({
            message: "任务名称不能为空",
            type: 'warning',
        });
        return false
    }
    if (taskModel.value.startIndex == undefined || taskModel.value.startIndex < 0) {
        ElMessage({
            message: "起始表索引不能为空，且不小于0",
            type: 'warning',
        });
        return false
    }
    if (taskModel.value.taskCount == undefined || taskModel.value.taskCount <= 0) {
        ElMessage({
            message: "数量不能为空，且不小于0",
            type: 'warning',
        });
        return false
    }
    if (taskModel.value.taskPeriod == undefined || taskModel.value.taskPeriod <= 0) {
        ElMessage({
            message: "写入周期不能为空，且不小于0",
            type: 'warning',
        });
        return false
    }

    if (taskModel.value.taskThread == undefined || taskModel.value.taskThread <= 0) {
        ElMessage({
            message: "线程数量不能为空，且不小于0",
            type: 'warning',
        });
        return false
    }
    if (taskModel.value.taskPrefix == undefined || taskModel.value.taskPrefix == "") {
        ElMessage({
            message: "表前缀不能为空",
            type: 'warning',
        });
        return false
    }
    return true
}

/**
 * 编辑操作
 */
const btn_editTask = (cellData) => {
    let tempData = Object.assign({}, cellData);
    taskModel.value = tempData;
    taskDialogVisible.value = true;
}
/**
 * 删除操作
 */
const btn_deleteTask = (cellData) => {
    if (cellData.taskStatue == "启动") {
        ElMessage({
            message: '该任务已启动，请先停止再删除',
            type: 'error',
        });
        return;
    }
    ElMessageBox.confirm('请确认是否删除该表记录?')
        .then(() => {
            let params = [];
            params.push(cellData);
            deleteTask(params).then(r => {
                searchAllTask();
            });
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })
}

/**
 * 启动任务
 */
const btn_startTask = (cellData) => {
    if (cellData.taskStatue == "启动") {
        ElMessage({
            message: '该任务已启动',
            type: 'error',
        });
        return;
    }
    ElMessageBox.confirm('请确认启动该任务?')
        .then(() => {
            let params = [];
            cellData['tablePre'] = tableModel.value.prefix
            cellData['tDengineConfigDto'] = databaseModel.value
            params.push(cellData);
            startTask(params).then(r => {
                ElMessage({
                    message: '任务已启动',
                    type: 'success',
                });
                searchAllTask();
            });
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        });
}

/**
 * 停止任务
 */
const btn_stopTask = (cellData) => {
    if (cellData.taskStatue == "停止") {
        ElMessage({
            message: '该任务已停止',
            type: 'error',
        });
        return;
    }
    ElMessageBox.confirm('请确认停止该任务?')
        .then(() => {
            let params = [];
            cellData['tablePre'] = tableModel.value.prefix
            cellData['tDengineConfigDto'] = databaseModel.value
            params.push(cellData);
            stopTask(params).then(r => {
                ElMessage({
                    message: '任务已停止',
                    type: 'error',
                });
                searchAllTask();
            });
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        });
}


/**
 * 启动全部任务
 */
const btn_startAllTask = () => {
    ElMessageBox.confirm('请确认全部启动任务?')
        .then(() => {
            var params = tableModel.value
            params['tDengineConfigDto'] = databaseModel.value
            var params2 = writeRules.value
            params2['createTableDto'] = params
            startAllTask(params2).then(r => {
                ElMessage({
                    message: '任务已启动',
                    type: 'success',
                });
                searchAllTask();
            });
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        });
}

/**
 * 停止全部任务
 */
const btn_stopAllTask = () => {
    ElMessageBox.confirm('请确认全部停止任务?')
        .then(() => {
            var params = tableModel.value
            params['tDengineConfigDto'] = databaseModel.value
            var params2 = writeRules.value
            params2['createTableDto'] = params
            stopAllTask(params2).then(r => {
                ElMessage({
                    message: '任务已停止',
                    type: 'error',
                });
                searchAllTask();
            });
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        });
}

const formatDate = (row) => {
    // 获取单元格数据
    let datac = row.taskLastwritetime
    let dtc = new Date(datac)
    //获取月,默认月份从0开始
    let dtuMonth = dtc.getMonth() + 1
    //获取日
    let dtuDay = dtc.getDate()
    //处理1-9月前面加0
    if (dtuMonth < 10) {
        dtuMonth = "0" + (dtc.getMonth() + 1)
    }
    //处理1-9天前面加0
    if (dtuDay < 10) {
        dtuDay = "0" + dtc.getDate()
    }
    //获取小时
    let dtuHours = dtc.getHours()
    //处理1-9时前面加0
    if (dtuHours < 10) {
        dtuHours = "0" + dtc.getHours()
    }
    //获取分钟
    let dtuMinutes = dtc.getMinutes()
    //处理1-9分前面加0
    if (dtuMinutes < 10) {
        dtuMinutes = "0" + dtc.getMinutes()
    }
    //获取秒
    let dtuSeconds = dtc.getSeconds()
    //处理1-9秒前面加0
    if (dtuSeconds < 10) {
        dtuSeconds = "0" + dtc.getSeconds()
    }
    //组装年月日时分秒,按自己的要求来
    return dtc.getFullYear() + "-" + dtuMonth + "-" + dtuDay + " " + dtuHours + ":" + dtuMinutes + ":" + dtuSeconds
}

/**
 * 批量插入
 */
const batchInsert = () => {
    ElMessageBox.confirm('请确认写入规则,执行历史值的批量写入！')
        .then(() => {
            batchInsertInfo();
        })
        .catch(() => {
            ElMessage({
                message: '已取消',
                type: 'success',
            });
        })
}
const batchInsertInfo = () => {
    if (beginWriteLoading.value)
        return
    if (!justifyCreateTablesParamsValid() || !justifyInitDatabaseParamsValid() || !justifyWriteRulesParamsValid())
        return
    beginWriteLoading.value = true
    var params = tableModel.value
    params['tDengineConfigDto'] = databaseModel.value
    var params2 = writeRules.value
    params2['createTableDto'] = params
    var loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    });
    batchInsertTime.value = 0;
    var intervalId = setInterval(() => {
        getDOCount(loading)
    }, 1000);
    batchInsertInfoWrite(params2).then(res => {
        if (res.code == '200') {
            batchInsertTime.value = res.data;
            ElMessage({
                message: res.data,
                type: 'success',
            });
        } else {
            ElMessage({
                message: res.msg,
                type: 'warning',
            });
        }
        beginWriteLoading.value = false;
        loading.close();
        clearInterval(intervalId);
    }).catch(res => {
        beginWriteLoading.value = false;
        loading.close();
        clearInterval(intervalId);

        ElMessage({
            message: "服务器出错",
            type: 'warning',
        });
    });
}
const getDOCount = (val) => {

    getDoingCount().then(res => {
        if (res.code == '200') {
            val.setText("已执行：" + res.data);
        } else {
        }
    }).catch(res => {
    });
}

</script>
<style scoped>
.formItemDialog {
    width: 130px;
}

.formItem {
    width: 200px;
}
</style>